<template>
	<view class="content">
		<view class="content_navbar">
			<u-navbar :is-mp-wx="true" :border-bottom="false" :is-back="false" :background="{ background: '#00D075' }">
				<template v-slot:content>
					<view class="u-flex u-row-between u-font-36 u-font-weight u-white-100 u-p-l-30 u-p-r-30"
						style="color:#fff">
						<view>聊天</view>
						<image style="width: 45rpx;height: 45rpx;" src="../../static/personal/news2.png"
							@click="toSystem"></image>
						<!-- <u-icon name="bell" size="48" color="#fff" @click="toSystem"></u-icon> -->
					</view>
				</template>
			</u-navbar>

			<view class="content_tabs u-border-bottom u-flex u-row-between">
				<view class="u-flex-1 u-flex" style="flex-direction: column;" v-for="(item,index) in data.tabs"
					:key="index" @click="$u.throttle(handleList(index), 2000)">
					<u-image :src="item.src" width="100" height="100" mode="widthFix"></u-image>
					<view class="u-m-t-10">
						{{item.label}}
					</view>
				</view>
			</view>
		</view>
		<z-paging ref="paging" :auto="false" :fixed="false" :auto-scroll-to-top-when-reload="false"
			:auto-clean-list-when-reload="false" :loading-more-enabled="false" :height="data.height" v-model="dataList"
			@query="queryList">
			<template v-for="(item,index) in dataList" :key="item.id">
				<u-swipe-action>
					<u-swipe-action-item :options="item.options" @click="swipeActionClick($event,item,index)"
						:ref="el => { if (el) swipeAction[index]=el}">
						<view class="content_item u-flex u-border-bottom"
							:class="item.stick == 1 ? 'content_item content_item--stick' : 'content_item'"
							@click="throttle(item)">
							<view style="position: relative;">
								<u-avatar :src="item.avatar"></u-avatar>
								<view class="badge" v-if="item.new > 0"></view>
							</view>
							<view class="u-m-l-20 u-flex-1">
								<view class="u-flex u-row-between">
									<view v-if="data.utype == 1" class="u-font-32 u-font-weight u-white-40 u-line-1">
										{{item.nickname}}
									</view>
									<view v-if="data.utype == 2" class="u-font-32 u-font-weight u-white-60 u-line-1">
										{{item.detail}}
									</view>
									<view class="u-font-14" style="color: #8A8888;">
										{{item.updatetime}}
									</view>
								</view>
								<view v-if="data.utype == 1" class="u-m-t-10 u-font-14 u-flex u-white-60"
									style="color: #8a8888;">
									<view class="u-line-1">
										{{item.last_message}}
									</view>
								</view>
								<view v-if="data.utype == 2" class="u-m-t-10 u-font-14 u-flex" style="color: #8a8888;">
									<view class="u-m-r-10" style="color: #333333;">{{item.nickname}}</view>
									<view class="u-m-r-10">正在与您沟通</view>
									<view class="u-line-1" style="color: #ff7725;width: 200rpx;">{{item.jobname}}</view>
								</view>
							</view>
						</view>
					</u-swipe-action-item>
				</u-swipe-action>
			</template>
		</z-paging>

		<u-modal v-model="data.isStick" title="系统提示"
			:content="`确定把${data.chatItem.nickname}${data.chatItem.stick == 1? '取消' : '设为'}置顶？`" show-cancel-button
			@cancel="data.isStick =false" @confirm="stickConfirm"></u-modal>

		<u-modal v-model="data.isMsgDel" title="系统提示" content="确定删除此对话吗？" show-cancel-button
			@cancel="data.isMsgDel =false" @confirm="confirm"></u-modal>

		<u-modal v-model="data.isBlacklist" title="系统提示" content="您已屏蔽对方，如需继续聊天请先解除屏蔽" show-cancel-button
			confirm-text="解除屏蔽" @concel="data.isBlacklist =false" @confirm="blackListConfirm"></u-modal>
	</view>
</template>

<script setup>
	import {
		nextTick,
		reactive,
		ref,
		watch
	} from "vue";
	import {
		onReady,
		onShow
	} from '@dcloudio/uni-app'
	import {
		useUserIm
	} from '@/stores/userIm'
	import {
		useUserStore
	} from '@/stores/userInfo.js'
	import {
		storeToRefs
	} from 'pinia'
	const IM = useUserIm()
	const {
		isLogin
	} = storeToRefs(useUserStore())
	const data = reactive({
		utype: 0,
		tabs: [],
		// 列表高度
		height: '',
		// 置顶弹框
		isStick: false,
		// 删除弹框
		isMsgDel: false,
		// 聊天对象信息
		chatItem: {},
		// 黑名单弹框
		isBlacklist: false,
		moveIndex: -1, //用于记录滑动下标
		imdisabled: false,
		imMessage: ''
	})
	const paging = ref(null)
	let dataList = ref([])
	onShow(() => {
		if (!isLogin.value) return uni.$u.route('/pages/login/login')
		data.utype = uni.getStorageSync('utype')
		getUtypeTabs()
		imWindowGlobal()
	})
	onReady(() => {
		nextTick(() => {
			getListHeight()
		})
	})
	// 监听消息更新回调
	watch(
		() => ([IM.messagelist, IM.IsUpdataChatList]), (nv) => {
			if (!isLogin.value) return
			nextTick(() => {
				if (nv[0] || nv[1] != 0) {
					paging.value.reload()
				}
			})
		}, {
			immediate: true,
			deep: true
		}
	)
	const getUtypeTabs = () => {
		if (data.utype == 1) {
			data.tabs = [{
				label: '收到投递',
				src: '/static/message/im-list-get-delivery.png'
			}, {
				label: '我的下载',
				src: '/static/message/im-list-download.png'
			}, {
				label: '我的收藏',
				src: '/static/message/im-list-collection.png'
			}, {
				label: '面试邀请',
				src: '/static/message/im-list-interview.png'
			}]
		} else {
			data.tabs = [{
				label: '谁看过我',
				src: '/static/message/tabs_1.png'
			}, {
				label: '我的投递',
				src: '/static/message/tabs_2.png'
			}, {
				label: '我的收藏',
				src: '/static/message/tabs_3.png'
			}, {
				label: '面试通知',
				src: '/static/message/tabs_4.png'
			}]
		}
	}
	// 跳转列表页面
	const handleList = (index) => {
		if (data.utype == 1 && uni.getStorageSync('next_code') == 50004) {
			uni.$u.route('pages/pagesPersonal/set/auth/auth')
			return
		}
		switch (index) {
			case 0:
				uni.$u.route('pages/pagesPersonal/followed/followed')
				break;
			case 1:
				uni.$u.route('pages/pagesPersonal/deliver/deliver')
				break;
			case 2:
				uni.$u.route('pages/pagesPersonal/collect/collect')
				break;
			case 3:
				uni.$u.route('pages/pagesMessage/interview/interview')
				break;
		}
	}
	// 节流方法
	const throttle = (item) => {
		if (item.show) return
		uni.$u.throttle(() => handleIsBlackList(item), 1000)
	}
	// 跳转会话详情
	const jumpImShow = (item) => {
		if (data.imdisabled) return uni.$u.toast(data.imMessage)
		IM.setimChatid(item.chat_id)
		uni.$u.route('pages/pagesMessage/detail', {
			item: decodeURIComponent(JSON.stringify(item))
		})
	}
	// 解除黑名单弹窗
	const blackListConfirm = async () => {
		let res = await IM.getBlacklistDel(data.chatItem.chat_id)
		if (res) jumpImShow(data.chatItem)
	}
	// 检测对方是否在黑名单
	const handleIsBlackList = async (blackItem) => {
		let res = await IM.getBlacklistCheck(blackItem.chat_id)
		// 0 没有屏蔽
		// 1 您已屏蔽对方，如需继续聊天请先解除屏蔽
		// 2 您已被对方加入黑名单，无法继续与TA聊天哦
		if (res == 1) {
			data.isBlacklist = true
			data.chatItem = blackItem
		} else if (res == 2) {
			uni.$u.toast('您已被对方加入黑名单，无法继续与TA聊天哦')
		} else {
			jumpImShow(blackItem)
		}
	}
	// 删除弹窗确认事件
	const confirm = async () => {
		await IM.getRemoveChat(data.chatItem.chat_id)
		dataList.value.forEach((item, index) => {
			if (item.chat_id == data.chatItem.chat_id) {
				dataList.value.splice(index, 1)
			}
		})
		closeSwipeAction()
	}
	// 置顶弹窗确认事件
	const stickConfirm = async () => {
		await IM.getChatStick(data.chatItem.chat_id, data.chatItem.stick)
		paging.value.reload()
		closeSwipeAction()
	}
	const swipeAction = ref([])
	const closeSwipeAction = () => {
		let test = swipeAction.value[data.moveIndex]
		if (data.moveIndex != -1) {
			test.closeHandler()
		}
	}
	const swipeActionClick = (e, item, index) => {
		// 点击置顶 或 取消置顶
		if (e.index == 0) {
			data.isStick = true
		}
		// 点击删除
		if (e.index == 1) {
			data.isMsgDel = true
		}
		data.chatItem = item
		data.moveIndex = index
	}
	// 跳转系统消息页
	const toSystem = () => {
		uni.$u.route('pages/pagesMessage/system')
	}
	// 全局聊天检测
	const imWindowGlobal = async () => {
		try {
			let res = await uni.$u.api.imWindowGlobal()
			// next 为空可以使用聊天
			if (res.next == '') {
				data.imdisabled = false
				data.imMessage = ''
				if (IM.imToken.value == '') {
					IM.setImToken()
				} else {
					paging.value.reload()
				}
			}
		} catch (err) {
			data.imdisabled = true
			data.imMessage = err.message
		}
	}
	// 获取列表展示高度
	const getListHeight = async () => {
		let res = await uni.$u.getRect('.content_navbar');
		if (res) {
			data.height = (uni.$u.sys().windowHeight - res.height) + 'px'
		}
	}
	// 获取消息列表数据
	const queryList = async () => {
		let res = await IM.getUserList()
		res = res.map(item => {
			item.options = [{
					image: '/static/message/topping.png',
					style: {
						backgroundColor: '#fff'
					}
				},
				{
					image: '/static/message/delete.png',
					style: {
						backgroundColor: '#fff'
					}
				}
			]
			if (item.stick == 1) {
				item.options[0].image = '/static/message/noTopping.png'
				item.options[0].style.backgroundColor = '#f9f9f9'
				item.options[1].style.backgroundColor = '#f9f9f9'
			}
			return item
		})
		nextTick(() => {
			paging.value.complete(res)
		})
	}
</script>

<style lang="scss" scoped>
	.content {
		&_tabs {
			padding: 30rpx 0
		}

		&_item {
			padding: 30rpx 20rpx;

			&--stick {
				background-color: #f9f9f9;
			}

			.badge {
				position: absolute;
				right: -3px;
				top: -3px;
				width: 10px;
				height: 10px;
				background: #ff4c56;
				color: #fff;
				font-size: 10px;
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}
	}
</style>